package net.aiotos.common.util;

import java.io.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * iO读取
 * @author iotos
 *
 */
public class ReadIO {
	
	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory.getLogger(ReadIO.class);
	/**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFile(File file) {
    	String result = "";
        if(!(file.exists() && file.isFile())) {
            return "";
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
            	result += tempString;
            }
            reader.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return result;
    }  
    
   /**
    * 写入本地文件
    * @throws IOException 
    **/
    public  static void writeFile(String content, File file){
    	// write string to file
        FileWriter writer = null;
        BufferedWriter bw = null;
		try {
		    // 判定文件是不是存在，否则创建
            if(!(file.exists() && file.isFile())) {
                file.createNewFile();
            }
			writer = new FileWriter(file,false);
		    bw = new BufferedWriter(writer);
		    bw.write(content);
		    bw.close();
		    writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != bw) {
					bw.close();
				}
				if (null != writer) {
					   writer.close();
				}  
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			
		}
    }
}
